package com.uchedao.seller.service;

import android.app.Service;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.nostra13.universalimageloader.utils.L;
import com.uchedao.seller.config.GlobalInfo;
import com.uchedao.seller.db.DbHelper;
import com.uchedao.seller.module.Draft;
import com.uchedao.seller.module.Photo;
import com.uchedao.seller.module.ResultIntArrayPics;
import com.uchedao.seller.module.Skeleton;
import com.uchedao.seller.util.CoverImageUtil;
import com.uchedao.seller.util.ProgressDialogUtil;
import com.uchedao.seller.util.T;
import com.uchedao.seller.util.ToastUtil;
import com.uchedao.seller.util.UploadPicUtil;
import com.uchedao.seller.util.Util;

import java.io.File;
import java.io.IOException;

/**
 * Created by hang on 2015/10/9.
 */
public class UpCarPhotoService extends Service {

    public final static String ACT_UPLOAD_SERVICE = "com.uchedao.vehicledetection.service.UpCarPhotoService";

    private UploadPicUtil upUtil;
    private Draft draft;
    private int reqCount;
    private boolean upPaintCover = false; // 漆膜厚度示意图是否上传成功
    private boolean upkeletonCover = false; // 事故勘察示意图是否上传成功

    private int succeedCount;
    private int failedCount;

    private boolean isUploading;
    private boolean isDestory;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        isDestory = false;
        upUtil = new UploadPicUtil(this);
    }

    @Override
    public void onDestroy() {
        isDestory = true;
        super.onDestroy();
    }

    @Override
    @Deprecated
    public void onStart(Intent intent, int startId) {
        if (isUploading) {
            T.showShort(this, "正在提交");
            return;
        }

        isUploading = true;
//        ProgressDialogUtil.showProgressDlg(this, "提交车检图片");
        upkeletonCover = false;
        upPaintCover = false;
        reqCount = 0;
        succeedCount = 0;
        failedCount = 0;

        uploadPaintCover();     // 上传漆膜厚度示意图
        uploadkeletonCover();   // 上传事故勘察示意图
        draft = GlobalInfo.draft;
        upload(draft.condition.paint_surface);  // 上传漆面检测
        upload(draft.condition.guise);  // 外观检测
        upload(draft.condition.interior);   // 内饰检测
        upload(draft.accident.skeletons);   // 结构件
        upload(draft.photo);    // 车辆照片
    }

    /**
     * 上传漆膜厚度示意图
     */
    private void uploadPaintCover() {
        ImageView iv = new ImageView(this);
        Bitmap hasFix = CoverImageUtil.createPaintCoverView(GlobalInfo.draft.condition.paint_thickness, iv);
//        if (!hasFix) {
////            return;
//        }

//        iv.setDrawingCacheEnabled(true);
//        iv.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
//                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
//        iv.layout(0, 0, iv.getMeasuredWidth(), iv.getMeasuredHeight());
//        iv.buildDrawingCache();

        File file = new File(GlobalInfo.PIC_PATH, System.currentTimeMillis() + ".jpg");
        try {
            Util.saveBitmap2File(hasFix, file);
        } catch (IOException e) {
            e.printStackTrace();
            ToastUtil.showToastLong("保存漆膜检测示意图失败:" + e.getMessage());
        }

        String filePath = file.getAbsolutePath();
        UploadPicUtil.UpSinglePicCallback callback = new UploadPicUtil.UpSinglePicCallback() {
            @Override
            public void uploadCallback(boolean isSucceed, String result, String moduleName) {
                System.out.println("isSucceed:" + isSucceed + ";result:" + result);
                reqCount--;
                upPaintCover = isSucceed;
                if (isSucceed) {
                    succeedCount++;
                    GlobalInfo.draft.condition.paintPicUrl = result;
                    submitAfterUpPic();
                } else {
                    failedCount++;
                    submitAfterUpPic();
//                    T.showShort(UpCarPhotoService.this, moduleName + ":" + result + "上传失败");
                }
            }
        };
        reqCount++;
        upUtil.upSinglePic("漆膜厚度示意图", filePath, callback);
        if (hasFix != null)
            hasFix.recycle();
    }

    /**
     * 上传结构检测示意图
     */
    private void uploadkeletonCover() {
        Bitmap bitmap = CoverImageUtil.getSkeletonCoverBitmap(this, GlobalInfo.draft.accident.skeletons);
        if (bitmap == null) {
            return;
        }
        File file = new File(GlobalInfo.PIC_PATH, System.currentTimeMillis() + ".jpg");
        L.w("filePath = " + file.getAbsolutePath());
        try {
            Util.saveBitmap2File(bitmap, file);
        } catch (IOException e) {
            e.printStackTrace();
            ToastUtil.showToastLong("保存结构检测示意图失败:" + e.getMessage());
            return;
        }

        String filePath = file.getAbsolutePath();
        UploadPicUtil.UpSinglePicCallback callback = new UploadPicUtil.UpSinglePicCallback() {
            @Override
            public void uploadCallback(boolean isSucceed, String result, String moduleName) {
                System.out.println("isSucceed:" + isSucceed + ";result:" + result);
                reqCount--;
                upkeletonCover = isSucceed;
                if (isSucceed) {
                    succeedCount++;
                    GlobalInfo.draft.accident.skeletonPicUrl = result;
                    submitAfterUpPic();
                } else {
                    failedCount++;
                    submitAfterUpPic();
//                    T.showShort(UpCarPhotoService.this, moduleName + ":" + result + "上传失败");
                }
            }
        };
        reqCount++;
        upUtil.upSinglePic("漆膜检测示意图", filePath, callback);
        if (bitmap != null)
            bitmap.recycle();
    }

    /**
     * 上传图片
     */
    private void upload(final Photo[] photos) {
        String filePath = null;

        // 上传漆面检测图片
        for (final Photo photo : photos) {
            if (photo == null) {
                L.i("photo==null");
                continue;
            }
            filePath = photo.pic_path;

            final String finalFilePath = filePath;
            UploadPicUtil.UpSinglePicCallback callback = new UploadPicUtil.UpSinglePicCallback() {
                @Override
                public void uploadCallback(boolean isSucceed, String result, String moduleName) {
                    System.out.println("isSucceed:" + isSucceed + ";result:" + result);
                    reqCount--;
                    if (isSucceed) {
                        succeedCount++;
                        photo.pic_url = result;
//                        if (checkPhoto(photos))
//                            submitAfterUpPic();
                    } else {
                        failedCount++;
//                        submitAfterUpPic();
//                        T.showShort(UpCarPhotoService.this, moduleName + ":" + result + "上传失败");
                    }
                    submitAfterUpPic();
                }
            };
            reqCount++;
            upUtil.upSinglePic("车辆照片", filePath, callback);
        }
    }

    private void upload(final Skeleton[] skeletons) {
        String filePath = null;

        for (final Skeleton skeleton : skeletons) {
            if (skeleton == null) {
                L.i("skeleton==null");
                continue;
            }
            skeleton.pic_url_list.clear();
            for (int i = 0; i < skeleton.pic_path_list.size(); i++) {
                filePath = skeleton.pic_path_list.get(i);

                final String finalFilePath = filePath;
                UploadPicUtil.UpSinglePicCallback callback = new UploadPicUtil.UpSinglePicCallback() {
                    @Override
                    public void uploadCallback(boolean isSucceed, String result, String moduleName) {
                        System.out.println("isSucceed:" + isSucceed + ";result:" + result);
                        reqCount--;
                        if (isSucceed) {
                            succeedCount++;
                            skeleton.pic_url_list.add(result);
//                            if (checkSkeleton(skeletons))
//                                submitAfterUpPic();
                        } else {
                            failedCount++;
//                            submitAfterUpPic();
//                            T.showShort(UpCarPhotoService.this, moduleName + ":" + result + "上传失败");
                        }
                        submitAfterUpPic();
                    }
                };
                reqCount++;
                upUtil.upSinglePic("结构件图片", filePath, callback);
            }
        }
    }

    private void upload(final ResultIntArrayPics[] resultIntArrayPics) {
        String filePath = null;

        // 上传漆面检测图片
        for (final ResultIntArrayPics arrayPic : resultIntArrayPics) {
            if (arrayPic == null) {
                L.i("arrayPic==null");
                continue;
            }

            arrayPic.pic_url_list.clear();
            for (int i = 0; i < arrayPic.pic_path_list.size(); i++) {
                filePath = arrayPic.pic_path_list.get(i);

                final String finalFilePath = filePath;
                UploadPicUtil.UpSinglePicCallback callback = new UploadPicUtil.UpSinglePicCallback() {
                    @Override
                    public void uploadCallback(boolean isSucceed, String result, String moduleName) {
                        System.out.println("isSucceed:" + isSucceed + ";result:" + result);
                        reqCount--;
                        if (isSucceed) {
                            succeedCount++;
                            arrayPic.pic_url_list.add(result);
//                            if (checkResultIntArrayPics(resultIntArrayPics))
//                                submitAfterUpPic();
                        } else {
                            failedCount++;
//                            submitAfterUpPic();
//                            T.showShort(UpCarPhotoService.this, moduleName + ":" + result + "上传失败");
                        }
                        submitAfterUpPic();
                    }
                };
                reqCount++;
                upUtil.upSinglePic("综合检测照片", filePath, callback);
            }
        }
    }

    /**
     * 判断车辆照片是否全部上传
     */
    public boolean checkPhoto(Photo[] photos) {
        for (final Photo photo : photos) {
            if (photo == null) {
                L.i("photo==null");
                continue;
            }
            if (TextUtils.isEmpty(photo.pic_url))
                return false;
        }
        return true;
    }

    /**
     * 判断结构件是否全部上传
     */
    public boolean checkSkeleton(Skeleton[] skeletons) {
        for (final Skeleton item : skeletons) {
            if (item == null) {
                L.i("arrayPic==null");
                continue;
            }
            if (item.pic_url_list == null || item.pic_url_list.size() != item.pic_path_list.size())
                return false;
        }
        return true;
    }

    /**
     * 判断漆面检测/外观检测是否全部上传
     */
    public boolean checkResultIntArrayPics(ResultIntArrayPics[] array) {
        for (final ResultIntArrayPics arrayPic : array) {
            if (arrayPic == null) {
                L.i("arrayPic==null");
                continue;
            }
            if (arrayPic.pic_url_list == null || arrayPic.pic_url_list.size() != arrayPic.pic_path_list.size())
                return false;
        }
        return true;
    }

    public void submitAfterUpPic() {
        if (reqCount > 0)
            return;

        ContentValues values = new ContentValues();
        values.put(DbHelper.KEY_DRAFT_CONDITION, toJson(draft.condition));
        values.put(DbHelper.KEY_DRAFT_PHOTO, toJson(draft.photo));
        values.put(DbHelper.KEY_DRAFT_ACCIDENT, toJson(draft.accident));

        // 保存
        GlobalInfo.dbHelper.updateDraf(GlobalInfo.draft.car_plate, values);

        isUploading = false;

        ProgressDialogUtil.dismissProgressDlg();
//        if (upPaintCover && upkeletonCover && checkResultIntArrayPics(draft.condition.paint_surface) &&
//                checkResultIntArrayPics(draft.condition.guise) && checkSkeleton(draft.accident.skeletons) && checkPhoto(draft.photo)) {
//            if(!isDestory) {
//                sendBroadcast(new Intent(MainActivity.MyReceiver.ACT_MAIN_RECEIVER));
//            }
//        } else {
//            T.showShort(this, "图片上传失败，请重新提交");
//        }

        if (!isDestory) {
//            Intent it = new Intent(MainActivity.MyReceiver.ACT_MAIN_RECEIVER);
//            it.putExtra("succeedCount", succeedCount);
//            it.putExtra("failedCount", failedCount);
//            sendBroadcast(it);
        }
    }

    private Gson gson = new Gson();

    /**
     * 不导出无Expose注解的字段
     *
     * @param src
     * @return
     */
    public String toJson(Object src) {
        return gson.toJson(src);
    }
}
